package com.rtz.util.job;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yl.util.MD5;
import com.yl.util.MapUtil;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

public class VerificationUtil {

	private final static Logger logger = Logger.getLogger(VerificationUtil.class);
	private static String KEY = "63f009caa2ce044aba2971d27b8e81d3";
	/**
	 * 验签
	 * @param dataMap
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean messageVerificationUtil(Map<String, Object> dataMap , String key) {

		Map<String, Object> head = (Map<String, Object>) dataMap.get("head");
		Map<String, Object> body = (Map<String, Object>) dataMap.get("body");
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		Map<String, Object> verificationMap = new HashMap<>(head);
		String sign = (String) verificationMap.get("sign");
		verificationMap.remove("sign");
		Map<String, Object> resMap = MapUtil.sortMapByKey(verificationMap);
		String headString = MapUtil.mapValueToString(resMap);
		String bodyString = gson.toJson(body, Map.class);
		
		String signString = headString+bodyString + key;
		logger.info("signString:"+signString);
		String signedString =  MD5.sign(signString, "",
				"utf-8");
		logger.info("signedString:"+signedString);
		logger.info("sign:"+sign);
		return sign.equalsIgnoreCase(signedString);
	}
	
	/**
	 * 签名
	 * @param dataMap
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String signVerificationUtil(Map<String, Object> dataMap) {

		Map<String, Object> head = (Map<String, Object>) dataMap.get("head");
		Map<String, Object> body = (Map<String, Object>) dataMap.get("body");
		
		Gson gson = new Gson();
		Map<String, Object> verificationMap = new HashMap<>(head);
		verificationMap.remove("sign");
		Map<String, Object> resMap = MapUtil.sortMapByKey(verificationMap);
		String headString = MapUtil.mapValueToString(resMap);
		String bodyString = gson.toJson(body, Map.class);
		
		String signString = headString+bodyString;
		logger.info("signString:"+signString);
		String signedString =  MD5.sign(signString, KEY,
				"utf-8");
		logger.info("signedString:"+signedString);
		return signedString;
	}

}
